package com.campus.controller;

import com.campus.pojo.Pager;
import com.campus.pojo.SysModule;
import com.campus.pojo.SysRole;
import com.campus.service.RoleService;
import com.campus.tools.Tree;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    RoleService service;
    JsonObject jsonObject;

    @RequestMapping("/getAllRole")
    @ResponseBody
    public Map<String,Object>  getAllRole(HttpServletRequest request,
                                          int page, int rows){

        String areaId = (String) request.getSession().getAttribute("AREANUMBER");//获取登录用户的所在区域
        Pager pager = new Pager();
        pager.setCurPage(page);
        pager.setPerPageRows(rows);
        Map<String,Object> result = new HashMap<>();
        result.put("pager",pager);
        result.put("areaId",areaId);
        List<SysRole> roleList = service.getAllRole(result);
        int count = service.count(result);
        result.clear();
        result.put("rows",roleList);
        result.put("total",count);
        return result;
    }

    @RequestMapping("/getModule")
    @ResponseBody
    public List<Tree> getModule(HttpServletRequest request, String roleCode){
        String areaId = (String) request.getSession().getAttribute("AREANUMBER");//获取登录用户的所在区域
        List<Tree> moduleList = service.getModules();//获取所有模块
        List<Tree> checkedModuleList = service.getModulesByRole(roleCode);//获取角色所属模块
        //根据所属模块 在所有模块list中打勾
        if (moduleList != null & checkedModuleList != null) {
            for (Tree tree : moduleList){
                if (checkedModuleList.contains(tree)){
                    tree.setChecked(true);
                }
                tree.setOpen(true);//设置为展开
            }
        }
        return moduleList;
    }

    @RequestMapping("/bindModule")
    @ResponseBody
    public void bindModule(HttpServletResponse response,HttpServletRequest request,
                           String roleCode,String mids) throws IOException {

        String areaId = (String) request.getSession().getAttribute("AREANUMBER");//获取登录用户的所在区域
        List<Tree> treeList = service.getModulesByRole(roleCode); //获取角色所属模块 修改之前A
        if (treeList == null)
            treeList = new ArrayList<>();
        String [] B = mids.split(","); //修改之后B
        //将A转换成字符串数组
        String[] A = new String[treeList.size()];
        int i = 0;
        for (Tree temp: treeList){
            A[i] = temp.getId();
            i++;
        }
        //将共有部分去掉， A剩余的需要删除，B剩余的需要添加
        for (i = 0; i < A.length; i++){
            for (int j=0;j<B.length;j++){
                if ( B[j] != null && A[i].contains(B[j])){
                    A[i] = B[j] = null;
                    break;
                }
            }
        }
        jsonObject = new JsonObject();
        try {
            for (String a : A){
                if (a == null)
                    continue;
                service.deleteRoleModules(roleCode,a);//删除
            }
            for (String b : B){
                if (b == null)
                    continue;
                service.addRoleModules(UUID.randomUUID().toString(),roleCode,b,areaId);//添加
            }
            jsonObject.addProperty("success",true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObject.addProperty("success",false);
        }finally {
            ServletOutputStream out = response.getOutputStream();
            out.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }
    }

    @RequestMapping("/getRoleList")
    @ResponseBody
    public Map<String,Object> getCheckedRole(String userCode,HttpServletRequest request){
        String areaId = request.getSession().getAttribute("AREANUMBER").toString();
        Map<String,Object> params = new HashMap<>();
        params.put("areaId",areaId);
        List<SysRole> roleList = service.getAllRole(params);//获取所有角色
        int count = 0;
        if (roleList != null && roleList.size()>0)
            count = roleList.size();
        params.clear();
        params.put("count",count);
        params.put("roleList",roleList);
        return params;
    }

    // 添加角色
    @RequestMapping(value = "/addRole", method = { RequestMethod.GET, RequestMethod.POST })
    public String addRole(String roleName, HttpServletRequest req, HttpServletResponse res) {
        jsonObject = new JsonObject();
        String areaId = req.getSession().getAttribute("AREANUMBER").toString();
        String exist = service.isExistName(roleName, "", areaId); // 添加时检验id不存在该id,所以设为空
        if (exist.equals("no")) {
            int result = service.addRole(roleName, areaId);
            jsonObject.addProperty("success", result);
        } else {
            jsonObject.addProperty("isExist", true);
        }
        try {
            ServletOutputStream jos = res.getOutputStream();
            jos.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 修改角色
    @RequestMapping(value = "/upRole", method = { RequestMethod.GET, RequestMethod.POST })
    public String upRole(SysRole role, HttpServletRequest req, HttpServletResponse res) {
        String areaId = req.getSession().getAttribute("AREANUMBER").toString();
        jsonObject = new JsonObject();
        int result = 0;
        // 查询是否存在该名称
        String exist = service.isExistName(role.getRoleName(), role.getRoleCode(), areaId);
        if (exist.equals("no")) {
            result = service.upRole(role);
            jsonObject.addProperty("success", result);
        } else {
            jsonObject.addProperty("isExist", true);
        }
        try {
            ServletOutputStream jos = res.getOutputStream();
            jos.write(jsonObject.toString().getBytes("utf-8"));
            jos.flush();
            jos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 删除role
    @RequestMapping(value = "/delRole", method = { RequestMethod.GET, RequestMethod.POST })
    public String delRole(String roleCode, HttpServletRequest req, HttpServletResponse res) {
        int result = service.delRole(roleCode);
        jsonObject = new JsonObject();
        jsonObject.addProperty("success", result);
        try {
            ServletOutputStream jos = res.getOutputStream();
            jos.write(jsonObject.toString().getBytes("utf-8"));
            jos.flush();
            jos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
